// packageA/pages/partList/partList.js
const app = getApp();
import CommonService from '../../../utils/service/commonService.js';
import Toast from '../../../miniprogram_npm/@vant/weapp/toast/toast';
import Dialog from '../../../miniprogram_npm/@vant/weapp/dialog/dialog';
const util = require('../../../utils/util');
import Base64 from '../../../utils/Base64.js';

Page({

  /**
   * 页面的初始数据
   */
  data: {
    //传参
    paramObj:{},
    //列表
    list:[],
    //页码
    page: 1,
    //是否无更多
    notMore: true,
    //无数据
    showNothing:false,
    //搜索关键词
    searchValue:'',
    //用户权限
    authority:null,  
    //配件分类列表
    categoryList:[],
    //选择框
    showSelect:false,
    //选择数据
    selectList:[],
    //当前选择
    selectField:'',
    //选择框标题
    selectTitle:'',
    //显示选择搜索框
    showSelectSearch:false,
    //配件厂家
    factory:{
      id:null,
      name:'配件厂家'
    },
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.setData({
      authority:app.globalData.authority
    })

    //获取配件分类
    this.getPartsCategoryList();  
  },

  //获取配件分类
  getPartsCategoryList(){
    Toast.loading({
      duration: 0,
      forbidClick: true,
      message: '加载中...'
    });
      
    let data = {
      otherFields: ['describe','categoryCode']
    }

    CommonService.getPartsCategoryTree(data).then(res => {
      if(res.data.data && res.data.data.result && res.data.data.result.length){
        this.setData({
          categoryList: res.data.data.result
        })        
      }
      //获取列表数据
      this.getList();
    }).catch((error) => {
      //获取列表数据
      this.getList();
    })
  },

  //获取列表数据
  getList(){
    Toast.loading({
      duration: 0,
      forbidClick: true,
      message: '加载中...'
    });

    let param = { 
      used: true,
      disabled: false,
      page: this.data.page,
      pageSize: 10
    }

    //搜索
    if(this.data.searchValue){
      param.keyword=this.data.searchValue;
    }

    //厂家
    if(this.data.factory.id) {
      param.factory=this.data.factory.id;
    }

    CommonService.partList(param).then(res => {
      Toast.clear();
      if(res.data.data && res.data.data.result && res.data.data.result.length) {
        let result=res.data.data.result;

        result.forEach(item => {
          //配件类型
          if(item.base && item.base.length) {
            let category = item.base[0].category;
            let name = this.getCategoriesName(category, 0, this.data.categoryList);
            //name=name.substring(0, name.length - 3);
            item.self_category=name;
          }
        }); 

        console.log('配件列表');
        console.log(result);

        this.setData({
          list: this.data.list.concat(result)
        })
      }else{
        this.setData({
          notMore: false
        })
        if(this.data.page==1){
          this.setData({
            showNothing: true
          })
        }else{
          Toast.fail('没有更多了');
        }
      }
    }).catch((error) => {
      this.setData({
        showNothing: true
      })
    })
  },

  //获取配件分类名称
  getCategoriesName(val, index, list) {
    let str = "";
    for (let i = 0; i < list.length; i++) {
      if (val[index] === list[i].id) {
        str += list[i].name;
        index++;
        if (index < val.length && (list[i].children && list[i].children.length > 0)) {
          str += " / ";
          return str += this.getCategoriesName(val, index, list[i].children);
        }
      }
    }
    return str;
  },

  //刷新列表和页码
  refreshListAndPage(){
    this.setData({
      list: [],
      page:1,
      notMore: true,
      showNothing: false
    })
    this.getList();
  },

  //获取搜索词
  onChangeSearch(e) {
    this.setData({
      searchValue: e.detail.value,
    })
  },

  //点击搜索
  onSearch(){
    this.refreshListAndPage();
  },
  
  //显示选择框
  onShowSelect(e){
    let dataset=e.currentTarget.dataset;
    let field=dataset.field;

    this.setData({
      showSelect: true,
      selectField: field
    }) 
    

    //配件厂家
    if(field=='factory'){
      this.setData({
        selectTitle: '配件厂家',
        showSelectSearch: true
      })
      this.getFactoryList();
    }
  },

  //隐藏选择框
  onCloseSelect(){
    this.setData({
      showSelect: false,
      valueSearch: '',
      disabled: false
    }) 
  },

  //确认选项
  onConfirmSelect(e){
    let selectField=this.data.selectField;
    let id=null,name=null,obj=null;

    //配件厂家
    if(selectField=='factory'){
      obj='factory';
    }

    if(id && name){
      this.setData({
        [id]:e.detail.value.id,
        [name]:e.detail.value.text
      })
    }

    if(obj){
      this.setData({
        [obj]:e.detail.value.obj
      })
    }

    this.onCloseSelect();
    this.refreshListAndPage();
  },

  //清除选项
  onCancelSelect(){
    let selectField=this.data.selectField;
    let id=null;

    //配件厂家
    if(selectField=='factory'){
      id='factory.id';
      let name='factory.name';
      this.setData({
        [name]:'配件厂家'
      })
    }

    if(id){
      this.setData({
        [id]:null
      })
    }    

    this.onCloseSelect();
    this.refreshListAndPage();
  },

  //选择框搜索
  onChangeSelectVal(e){
    let selectField=this.data.selectField;

    this.setData({
      valueSearch: e.detail
    }) 

    //配件厂家
    if(selectField=='factory'){
      this.getFactoryList();
    }
  },

  //查询配件厂家
  getFactoryList(){
    this.setData({
      selectList: []
    })

    let param = {
      isAuth: true,
      className: 'supplierFactories',
      data: {
        searchAll: true,  
        selectFields: ['id','name','factoryDepart'],
        sort: {id: -1}
      }
    }
    
    if(this.data.valueSearch){
      param.data.name='%' + this.data.valueSearch + '%';
    }

    CommonService.goFindList(param).then(res=>{
      if(res.data.data && res.data.data.result && res.data.data.result.length){
        let result=res.data.data.result;
        let arr=[];
        result.forEach(item => {
          arr.push({
            text: item.name,
            id: item.id,
            obj:{
              id: item.id,
              name: item.name,
              depart: item.factoryDepart,
            }
          });
        });

        this.setData({
          selectList: arr
        })
      }
    }).catch((error) => {
    })
  },

  //编辑
  goToEdit(e){  
    let detail=e.currentTarget.dataset.detail;
    let isRead=e.currentTarget.dataset.isread;

    //处理参数
    let params=[];
    if(detail.params && detail.params.length){
      detail.params.forEach(item => {
        params.push(item.key+':'+item.value)
      });
    }
    
    //处理规格
    let specs=[];
    if(detail.specs && detail.specs.length){
      detail.specs.forEach(item => {
        specs.push(item.key+':'+item.value)
      });
    }

    let obj={
      //查看/编辑
      isRead: isRead,
      //数据id
      id: detail.id,
      //类型
      self_category: detail.self_category,
      //参数
      self_params: params,
      //规格
      self_specs: specs
    }

    wx.navigateTo({
      url: "/packageA/pages/partAdd/partAdd?paramObj="+JSON.stringify(obj)
    })
  },

  //禁用
  onDisable(e){
    Dialog.confirm({
      title: '是否禁用当前配件信息',
      confirmButtonText:'禁用',
      cancelButtonText:'不禁用了'
    }).then(() => {
      let detail=e.currentTarget.dataset.detail;

      let param={
        className:'partsFactory',
        data:{
          id: detail.id,
          disabled: true
        }
      }

      CommonService.goSave(param).then(res=>{       
        if (res.statusCode == 200 && res.data.success == true){
          Toast.success('已禁用');
          setTimeout(() => {
            this.refreshListAndPage();
          }, 1000);
        }else{
          Toast.fail('操作失败，请联系管理员');
        }
      }).catch((error) => {
        Toast.fail('操作失败，请联系管理员');
      })

    }).catch(() => {
    });
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    if(this.data.notMore){
      this.setData({
        page: this.data.page + 1
      })
      this.getList();
    }
  }
})